package com.work.straighttalk.ui;

import android.media.AudioManager;
import android.media.RingtoneManager;
import android.media.SoundPool;
import android.net.Uri;
import android.os.Bundle;
import android.os.SystemClock;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AlphaAnimation;
import android.view.animation.Animation;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.hyphenate.chat.EMCallStateChangeListener;
import com.hyphenate.chat.EMClient;
import com.work.straighttalk.R;
import com.work.straighttalk.presenter.VoiceCallPImpl;
import com.work.straighttalk.presenter.i.VoiceCallPI;
import com.work.straighttalk.ui.i.VoiceCallVI;
import com.work.straighttalk.view.MyChronometer;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by dllo on 16/3/9.
 */
public class VoiceCallActivity extends CallActivity implements VoiceCallVI {


    @Bind(R.id.tv_call_state) TextView callStateTextView;
    @Bind(R.id.chronometer) MyChronometer chronometer;
    @Bind(R.id.tv_calling_duration) TextView durationTextView;
    @Bind(R.id.tv_nick) TextView nickTextView;
    @Bind(R.id.iv_mute) ImageView muteImage;
    @Bind(R.id.iv_handsfree) ImageView handsFreeImage;
    @Bind(R.id.ll_voice_control)LinearLayout voiceContronlLayout;
    @Bind(R.id.btn_hangup_call) Button hangupBtn;
    @Bind(R.id.btn_refuse_call) Button refuseBtn;
    @Bind(R.id.btn_answer_call) Button answerBtn;
    @Bind(R.id.ll_coming_call) LinearLayout comingBtnContainer;
    private boolean isMuteState;
    private boolean isHandsfreeState;
    private boolean endCallTriggerByMe = false;
    String st1;
    private boolean isAnswered;
    private boolean isComingCall;
    private VoiceCallPI voiceCallPI;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_voice_call);
        ButterKnife.bind(this);

        username = getIntent().getStringExtra("username");
        isComingCall = getIntent().getBooleanExtra("isComingCall", false);
        voiceCallPI = new VoiceCallPImpl(this);

        getWindow().addFlags(
                WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON | WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
                        | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED | WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);

        // 注册语音电话的状态的监听
        nickTextView.setText("116");
        voiceCallPI.Call(username, isComingCall);
        voiceCallPI.setConversation();
    }

    //拒绝接听
    @OnClick(R.id.btn_refuse_call)
    protected void refuseCall() {
        refuseBtn.setEnabled(false);
        handler.sendEmptyMessage(MSG_CALL_REJECT);
    }

    //接听电话
    @OnClick(R.id.btn_answer_call)
    protected void answerCall() {
        answerBtn.setEnabled(false);
        closeSpeakerOn();
        callStateTextView.setText("正在接听...");
        comingBtnContainer.setVisibility(View.INVISIBLE);
        hangupBtn.setVisibility(View.VISIBLE);
        voiceContronlLayout.setVisibility(View.VISIBLE);
        handler.sendEmptyMessage(MSG_CALL_ANSWER);
    }

    //挂断电话
    @OnClick(R.id.btn_hangup_call)
    protected void hangupCall() {
        hangupBtn.setEnabled(false);
        chronometer.stop();
        endCallTriggerByMe = true;
        callStateTextView.setText("正在挂断..");
        handler.sendEmptyMessage(MSG_CALL_END);
    }

    //静音开关
    @OnClick(R.id.iv_mute)
    protected void mute() {
        if (isMuteState) {
            // 关闭静音
            muteImage.setImageResource(R.mipmap.em_icon_mute_normal);
            audioManager.setMicrophoneMute(false);
            isMuteState = false;
        } else {
            // 打开静音
            muteImage.setImageResource(R.mipmap.em_icon_mute_on);
            audioManager.setMicrophoneMute(true);
            isMuteState = true;
        }
    }

    //免提开关
    @OnClick(R.id.iv_handsfree)
    protected void handsfree() {
        if (isHandsfreeState) {
            // 关闭免提
            handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_normal);
            closeSpeakerOn();
            isHandsfreeState = false;
        } else {
            handsFreeImage.setImageResource(R.mipmap.em_icon_speaker_on);
            openSpeakerOn();
            isHandsfreeState = true;
        }
    }


    @Override
    public void call() {
        soundPool = new SoundPool(1, AudioManager.STREAM_RING, 0);
        comingBtnContainer.setVisibility(View.INVISIBLE);
        hangupBtn.setVisibility(View.VISIBLE);
        st1 = "正在连接对方...";
        callStateTextView.setText(st1);
        handler.sendEmptyMessage(MSG_CALL_MAKE_VOICE);
    }

    @Override
    public void comingCall() {
        voiceContronlLayout.setVisibility(View.INVISIBLE);
        Uri ringUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE);
        audioManager.setMode(AudioManager.MODE_RINGTONE);
        audioManager.setSpeakerphoneOn(true);
        ringtone = RingtoneManager.getRingtone(this, ringUri);
        ringtone.play();
    }

    @Override
    public void cinnecting() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                callStateTextView.setText(st1);
            }
        });
    }

    @Override
    public void connected() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                callStateTextView.setText("已经和对方建立连接，等待对方接受...");
            }
        });
    }

    @Override
    public void acceptend() {
        handler.removeCallbacks(timeoutHangup);
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (soundPool != null)
                        soundPool.stop(streamID);
                } catch (Exception e) {
                }
                if (!isHandsfreeState)
                    closeSpeakerOn();
                //显示是否为直连，方便测试
                ((TextView) findViewById(R.id.tv_is_p2p)).setText(EMClient.getInstance().callManager().isDirectCall()
                        ? "Direct" : "Relay");
                chronometer.setVisibility(View.VISIBLE);
                chronometer.setBase(SystemClock.elapsedRealtime());
                // 开始记时
                chronometer.start();
                String str4 = "通话中...";
                callStateTextView.setText(str4);
                callingState = CallingState.NORMAL;
            }
        });
    }

    @Override
    public void disconnnected(EMCallStateChangeListener.CallError callError) {
        handler.removeCallbacks(timeoutHangup);
        final EMCallStateChangeListener.CallError fError = callError;
        runOnUiThread(new Runnable() {
            private void postDelayedCloseMsg() {
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                Log.d("AAA", "CALL DISCONNETED");
                                Animation animation = new AlphaAnimation(1.0f, 0.0f);
                                animation.setDuration(800);
                                findViewById(R.id.root_layout).startAnimation(animation);
                                finish();
                            }
                        });
                    }
                }, 200);
            }
            @Override
            public void run() {
            }
        });

    }

}

